package leetcode01_10;

import org.junit.Test;

/**
 将一个给定字符串根据给定的行数，以从上往下、从左到右进行 Z 字形排列。

 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时，排列如下：

 L   C   I   R
 E T O E S I I G
 E   D   H   N

 * @author shhjiang_001
 * @create 2020-03-08 20:49
 */
public class Solution06 {
    public String convert(String s, int numRows) {
        int n = numRows;
        if (n==1){
            return s;
        }
        StringBuffer[] sb = new StringBuffer[n];
        for(int m=0 ;m<n ;m++){
            sb[m] =new StringBuffer();
        }
        int p = s.length() / (2 * n - 2);
        for (int k = 0; k < p+1 ; k++){
            if (s.length()> (k*(2*n-2))){
                sb[0].append(s.charAt(k*(2*n-2)));
            }
            if (s.length()> (k*(2*n-2)+n-1)){
                sb[n-1].append(s.charAt(k*(2*n-2)+n-1));
            }
            int j= 1;
            for (int i = n-2;i > 0; i--){
                if (s.length()> (k*(2*n-2)+n-1-j)){
                    sb[i].append(s.charAt(k*(2*n-2)+n-1-j));
                }
                if (s.length()> (k*(2*n-2)+n-1+j)){
                    sb[i].append(s.charAt(k*(2*n-2)+n-1+j));
                }
                j++;
            }
        }
        String ans = "";
        for(int i = 0; i < n ;i++){
            ans = ans + sb[i].toString();
        }
        return ans;
    }
    public String convert1(String s, int numRows) {
        if (s == null || s.length() == 0 || numRows <= 1) return s;
        StringBuilder[] array = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) array[i] = new StringBuilder();
        int dir = 1;
        int index = 0;
        for (char c : s.toCharArray()) {
            array[index].append(c);
            index += dir;
            if (index == 0 || index == numRows - 1) dir = -dir;
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < numRows; i++) result.append(array[i]);

        return result.toString();
    }
    @Test
    public void converTest(){
        Solution06 solution = new Solution06();
        String s = solution.convert("hsfkhfiuewih", 4);
        String p = solution.convert1("hsfkhfiuewih", 4);
        System.out.println(s);
        System.out.println(p);
    }

}
